package com.alm.token.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.ActiveMioData;
import com.alm.token.ui.data.bean.CandyOrderDetilData;
import com.alm.token.ui.data.bean.CandyOrderListData;
import com.alm.token.ui.data.bean.DrawIndexData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.CandyView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.LanguageUtils;
import com.alm.token.utils.LogUtil;
import com.alm.token.utils.Utils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yzq.zxinglibrary.encode.CodeCreator;
//import com.uuzuche.lib_zxing.activity.CaptureActivity;
//import com.uuzuche.lib_zxing.activity.CodeUtils;
//import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class CandyActivity extends BaseActivity implements CandyView<Object> {

    @BindView(R.id.rightItem)
    TextView rightItem;
    @BindView(R.id.edt_candymoney)
    EditText edtCandymoney;
    @BindView(R.id.tv_candytypeshow)
    TextView tvCandytypeshow;
    @BindView(R.id.tv_candyshow)
    TextView tvCandyshow;
    @BindView(R.id.img_more)
    ImageView imgMore;
    @BindView(R.id.tv_changcandytypeshow)
    TextView tvChangcandytypeshow;
    @BindView(R.id.tv_changcandytype)
    TextView tvChangCandytype;
    @BindView(R.id.edt_candynumber)
    EditText edtCandynumber;
    @BindView(R.id.tv_balanc)
    TextView tvBalanc;
    @BindView(R.id.tv_bizhongtv)
    TextView tvBizhongtv;
    @BindView(R.id.tv_totalmoney)
    TextView tvTotalmoney;
    @BindView(R.id.tv_candyshow1)
    TextView tvCandyshow1;
    @BindView(R.id.tv_candycommit)
    TextView tvCandycommit;
    @BindView(R.id.tv_msg)
    TextView tvMsg;
    @BindView(R.id.tv_candypricenumber)
    TextView tvCandyPriceNumber;


    private List<ActiveMioData.DataBean> dataBeanList;//    moneyType : 2  name : MIO  yue : 0.0
    private ActiveMioData.DataBean dataBean;//moneyType : 2  name : MIO  yue : 0.0
    private String candyName = "MIO";
    private double candyBalanc = 0.00d, candyPrice = 0.00d, candyMin = 0.00d, candyMax = 0.00d, candyNum = 0.00d;
    private double candyTotalMio = 0.00d;
    private double candyQuantity = 0;
    private double candyJine = 0d;
    private int candyType = 1;//1随机2固定
    private int biSelect = 0;

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
//        rootView = LayoutInflater.from(CandyActivity.this).inflate(R.layout.activity_turnout_shoukuan, null);
        return R.layout.activity_candy;
    }

    @Override
    protected void initVariables() {

//        //设置EditText的显示方式为多行文本输入
//        edtInputadress.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
//        //文本显示的位置在EditText的最上方
//        edtInputadress.setGravity(Gravity.CENTER_VERTICAL);
//        edtInputadress.setText("");
//        //改变默认的单行模式
//        edtInputadress.setSingleLine(false);
//        //水平滚动设置为False
//        edtInputadress.setHorizontallyScrolling(false);
//        edtInputadress.setText("");
    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this).setTitle(getString(R.string.app_hint_redenvelope)).setRightText(getString(R.string.banner_hint_jilu));
//        edtInputmoney.addTextChangedListener(this);

        edtCandymoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 4) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 5);
                        edtCandymoney.setText(s);
                        edtCandymoney.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    edtCandymoney.setText(s);
                    edtCandymoney.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        edtCandymoney.setText(s.subSequence(0, 1));
                        edtCandymoney.setSelection(1);
                        return;
                    }
                }
                if (!TextUtils.isEmpty(s.toString())) {
                    candyTotalMio = Double.valueOf(s.toString());
                } else {
                    candyTotalMio = 0;
                }
                mathNumber(1);
            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });

        edtCandynumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    candyQuantity = Double.valueOf(s.toString());
                } else {
                    candyQuantity = 0;
                }
                mathNumber(2);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 变化的edt  方便更改edt对象
     * candyType  1随机2固定
     *
     * @param editType 1 edtCandymoney /  2 edtCandynumber
     */
    private void mathNumber(int editType) {
        LogUtil.d("candyType=" + candyType + " candyTotalMio=" + candyTotalMio + " candyQuantity=" + candyQuantity + " editType=" + editType);
        if (candyType == 1) {//随机
            if (candyTotalMio > candyBalanc) {
                showToast(getString(R.string.conversioncurrency_hint1_warn6));
                candyTotalMio = 0d;
                edtCandymoney.setText("");
            }
            candyJine = candyQuantity == 0 ? 0 : candyTotalMio;

        } else {//固定
            if (candyTotalMio * candyQuantity > candyBalanc) {
                showToast(getString(R.string.conversioncurrency_hint1_warn6));
                if (editType == 1) {
                    edtCandymoney.setText("");
                    candyTotalMio = 0d;
                } else {
                    edtCandynumber.setText("");
                    candyQuantity = 0d;
                }
            }
            candyJine = candyTotalMio * candyQuantity;
        }
        tvTotalmoney.setText(CommonUtil.saveToPoint4WithNo(candyJine));
        tvBalanc.setText(CommonUtil.saveToPoint4WithNo(candyBalanc - candyJine));
        tvCandyPriceNumber.setText("≈ $" + CommonUtil.saveToPoint2WithNo(candyJine * candyPrice));
        if (candyJine * candyPrice == 0) {
            tvCandyPriceNumber.setVisibility(View.INVISIBLE);
        } else {
            tvCandyPriceNumber.setVisibility(View.VISIBLE);
        }
        if (candyJine != 0) {
//            tvCandycommit.setBackground(getResources().getDrawable(R.drawable.blue_btn_bg1));
            tvCandycommit.setBackground(getResources().getDrawable(R.drawable.gradient_btn));
            tvCandycommit.setOnClickListener(this);
        } else {
            tvCandycommit.setBackground(getResources().getDrawable(R.drawable.gradient_btn_unclick));
            tvCandycommit.setOnClickListener(null);
        }
        if (candyQuantity > candyNum) {
            showToast(getString(R.string.tv_hint_candy_warm1, CommonUtil.saveToPoint4WithNo(candyNum)));
        }
        if (candyJine * candyPrice > candyMax) {
            showToast(getString(R.string.tv_hint_candy_warm3, CommonUtil.saveToPoint4WithNo(candyMax)));
        }
    }

    @Override
    protected void loadData() {
        preenter.getActiveMio();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_candyshow:
                if (dataBeanList != null && dataBeanList.size() > 1) {
                    showPopupMenu2(tvCandyshow);
                }
                break;
//            case R.id.tv_outmoneycommit:
//                dec1 = new DecimalFormat("0.0000");
//                if (number == 0) {
//                    showToast(getString(R.string.alphago_hint_warn5));
//                    break;
//                }
//                scanResult = edtInputadress.getText().toString();
//                if (scanResult.isEmpty() || !Utils.verifyUserName(scanResult)) {
//                    showToast(getString(R.string.profile_hint_warn2));
//                    break;
//                }
//                if (scanResult.length() < 4 || scanResult.length() > 18) {
//                    showToast(getString(R.string.profile_hint_warn3));
//                    break;
//                }
//                if (!Utils.verifyUserNameFL(scanResult)) {//[A-Za-z1-9]{2}
//                    showToast(getString(R.string.profile_hint_warn4));
//                    break;
//                }
//                UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
//                sysMsgBean.setTitle(getString(R.string.wallet_hint_warn2));
//                sysMsgBean.setContent(getString(R.string.wallet_hint_warn3, CommonUtil.saveToPoint4WithNo(number), tvBizhongshow.getText().toString()));
//                DialogUtils.showInfor1(this, sysMsgBean, (pwd) -> {
//                    verify();
//                });
//                break;
            case R.id.tv_candycommit:
                LogUtil.d("candyJine=" + candyJine + " candyQuantity=" + candyQuantity + " candyType=" + candyType);
                DialogUtils.enterPayPsw(this,  (pwd1) -> {
                    preenter.getSubmitHongBaoData(CommonUtil.saveToPoint4WithNo(candyJine),
                            (int) candyQuantity + "",
                            String.valueOf(candyType), dataBean.getMoneyType(), pwd1);

                });


                break;

            case R.id.tv_savebitmap:
                if (bodyBitmap == null) {
                    showToast(getString(R.string.network_loading_hint1));
                    break;
                }
                //存储权限
                RxPermissions rxPermissions = new RxPermissions(this);
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Observer<Boolean>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(Boolean granted) {
                                if (granted) {
                                    if (saveImageToGallery(CandyActivity.this, bodyBitmap, CommonUtil.getStringDate() + getString(R.string.profile_hint_item35))) {
                                        showToast(getString(R.string.profile_hint_item15));
                                        tvSavebitmap.setText(getString(R.string.profile_hint_item16));
                                    }
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                            }
                        });

                break;
            case R.id.tv_copy:
                if (xiazaiuri.isEmpty()) {
                    showToast(getString(R.string.network_loading_hint1));
                    break;
                }
                copyWalletAddress(xiazaiuri);
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.rightItem, R.id.tv_changcandytype})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rightItem:
                Intent intent = new Intent(this, VipOrderListActivity.class);
                intent.putExtra("intentType", 4);
                startActivity(intent);
                break;
            case R.id.tv_changcandytype:

                candyType = candyType == 1 ? 2 : 1;
                if (candyType == 1) {//随机红包糖果
                    tvCandytypeshow.setText(getString(R.string.deploy_hint_candymoney_ping));
                    tvChangcandytypeshow.setText(getString(R.string.deploy_hint_candymoney_ping_msg1));
                    tvChangCandytype.setText(getString(R.string.deploy_hint_candymoney_ping_msg2));
                    if (candyJine != 0) {
                        candyTotalMio = candyJine;
                        edtCandymoney.setText(CommonUtil.saveToPoint4WithNo(candyTotalMio));
                    }
                } else {//固定红包糖果
                    tvCandytypeshow.setText(getString(R.string.deploy_hint_candymoney_one));
                    tvChangcandytypeshow.setText(getString(R.string.deploy_hint_candymoney_one_msg1));
                    tvChangCandytype.setText(getString(R.string.deploy_hint_candymoney_one_msg2));
                    if (candyJine != 0) {
                        double dd = candyJine / candyQuantity;
                        if (String.valueOf(dd).indexOf(".") != -1 && String.valueOf(dd).split("\\.")[1].length() >= 4) {
                            BigDecimal b = new BigDecimal(dd);
                            candyTotalMio = b.setScale(4, BigDecimal.ROUND_HALF_DOWN).doubleValue();
                        } else {
                            candyTotalMio = dd;
                        }
                        edtCandymoney.setText(CommonUtil.saveToPoint4WithNo(candyTotalMio));
                    }
                }
                mathNumber(1);
                break;
        }
    }

    AlertDialog alert;

    private void verify() {
//        alert = DialogUtils.showVerify(this, (pwd, code) -> {
//            preenter.getTransfertransData(number + "", scanResult, bizhongType1 + "", code, pwd);
//        }, code1 -> {
//            if (MyApp.getUserData() != null && MyApp.getUserData().getData() != null && MyApp.getUserData().getData().getUser() != null) {
//                String phone = MyApp.getUserData().getData().getUser().getPhone();
//                preenter.getSmsCodeData(phone, "check", code1);
//            }
//        });
    }

    String scanResult = "";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    DecimalFormat dec1;

    public void showPopupMenu2(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局
        Menu menu = popupMenu.getMenu();
        for (ActiveMioData.DataBean dataBean : dataBeanList) {
            menu.add(dataBean.getName());
        }
        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);

        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                for (int i = 0; i < dataBeanList.size(); i++) {
                    if (item.getTitle().toString().equalsIgnoreCase(dataBeanList.get(i).getName())) {
                        if (dataBean.getMoneyType() == dataBeanList.get(i).getMoneyType()) {
                            showToast(getString(R.string.crowdfund_hint_warn3));
                            break;
                        }
                        biSelect = i;
                        initdata();
                        break;
                    }
                }
                return true;
            }
        });
        popupMenu.show();
    }

    @Override
    public void getData(Object o) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.common_loaderrritry));
        if (alert != null && alert.isShowing()) {
            alert.dismiss();
        }
    }

    @Override
    public void ShowProgress() {
        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }

    @Override
    public void getCode(RegisterData registerData) {
        if (registerData.getMsg().equalsIgnoreCase(getString(R.string.profile_hint_warn15))) {
            showToast(getString(R.string.profile_hint_warn14));
        } else {
            showToast(registerData.getMsg());
        }
    }

    private void initdata() {
        if (dataBeanList != null && dataBeanList.size() != 0) {
            dataBean = dataBeanList.get(biSelect);
        }
        if (dataBean != null) {
            candyBalanc = 0.00d;
            candyTotalMio = 0.00d;
            candyQuantity = 0;
            candyJine = 0d;
            edtCandymoney.setText("");
            edtCandynumber.setText("");

            candyPrice = dataBean.getPrice();
            candyMin = dataBean.getMin();
            candyMax = dataBean.getMax();
            candyNum = dataBean.getNum();
            candyName = dataBean.getName();
            candyBalanc = Double.valueOf(dataBean.getYue());
            tvCandyshow.setText(candyName);
            tvCandyshow1.setText(candyName);
            tvBizhongtv.setText(candyName);
            tvBalanc.setText(CommonUtil.saveToPoint4WithNo(candyBalanc));
            /**
             *  /**
             * min : 0.1
             * max : 100
             * price : 258.2700
             * num : 100
             */
            tvMsg.setText(getString(R.string.tv_hint_candy_warm1, CommonUtil.saveToPoint4WithNo(dataBean.getNum())) + ","
                    + getString(R.string.tv_hint_candy_warm2, CommonUtil.saveToPoint2WithNo(dataBean.getMin())) + ","
                    + getString(R.string.tv_hint_candy_warm3, CommonUtil.saveToPoint2WithNo(dataBean.getMax())));
        }
    }

    @Override
    public void getActiveMio(ActiveMioData activeMioData) {

        if (activeMioData.getStatus() == 0) {
            dataBeanList = activeMioData.getData();
            if (dataBeanList != null && dataBeanList.size() > 1) {
                tvCandyshow.setOnClickListener(this);
                imgMore.setVisibility(View.VISIBLE);
            } else {
                tvCandyshow.setOnClickListener(null);
                imgMore.setVisibility(View.INVISIBLE);
            }

            initdata();
        } else {
            showToast(activeMioData.getMsg());
        }
    }

    @Override
    public void getSubmitHongBaoData(RegisterData registerData) {
        if (registerData.getStatus() == 0) {

            if (!TextUtils.isEmpty(registerData.getData())) {

                candyBalanc = 0.00d;
                candyTotalMio = 0.00d;
                candyQuantity = 0;
                candyJine = 0d;
                edtCandymoney.setText("");
                edtCandynumber.setText("");
                preenter.getActiveMio();
                showpopwindow(registerData.getData());
            }
        } else {
            showToast(registerData.getMsg());
        }

    }

    PopupWindow p;

    private void showpopwindow(String uri) {
        xiazaiuri = uri;
        final View inflate = View.inflate(this, R.layout.layout_candy_qrcode, null);
        imgAdressqrcode = inflate.findViewById(R.id.img_adressqrcode);
        lyQrcodeBody = inflate.findViewById(R.id.ly_qrcodebody);


        if (LanguageUtils.getSetIndex() == 1) {
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_candy_bg1));
        } else if (LanguageUtils.getSetIndex() == 3){
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_candy_bg13));
        }else if (LanguageUtils.getSetIndex() == 4){
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_candy_bg14));
        }else {
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_candy_bg_en1));
        }

        LinearLayout lyQrcodeBodySmall = inflate.findViewById(R.id.ly_qrqdbody_small);
        if (LanguageUtils.getSetIndex() == 1) {
            lyQrcodeBodySmall.setBackground(getResources().getDrawable(R.drawable.icon_candy_qd_bg2));
        } else if (LanguageUtils.getSetIndex() == 3){
            lyQrcodeBodySmall.setBackground(getResources().getDrawable(R.drawable.icon_candy_qd_bg23));
        }else if (LanguageUtils.getSetIndex() == 4){
            lyQrcodeBodySmall.setBackground(getResources().getDrawable(R.drawable.icon_candy_qd_bg24));
        }else {
            lyQrcodeBodySmall.setBackground(getResources().getDrawable(R.drawable.icon_candy_qd_bg2_en));
        }

        inflate.findViewById(R.id.leftItem).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (p != null && p.isShowing()) {
                    p.dismiss();
                    p = null;
                }
            }
        });

        TextView tvright = inflate.findViewById(R.id.rightItem);
        tvright.setText("More");
        tvright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showPopwindow1();
            }
        });

        TextView title = inflate.findViewById(R.id.centerItem);
        title.setText(getString(R.string.profile_hint_item35).replace(".jpg", ""));

        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels * 3 / 4;         // 屏幕宽度（像素）
        int height = dm.heightPixels * 3 / 4;       // 屏幕高度（像素）

        p = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        p.setTouchable(true);
        p.setFocusable(true);
        p.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.color_cccccc)));
        p.setAnimationStyle(R.style.Animleft);
        p.showAtLocation(inflate, Gravity.CENTER, 0, 0);
        p.showAsDropDown(inflate, 100, 100);
        initAddressQRCode();
    }


    PopupWindow popWindow;

    private void showPopwindow1() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.activity_invite_select, null);

        tvSavebitmap = popView.findViewById(R.id.tv_savebitmap);
        tvCopy = popView.findViewById(R.id.tv_copy);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        if (popWindow == null) {
            popWindow = new PopupWindow(popView, width, Utils.dp2px(this, 130));
//            popWindow.setAnimationStyle(R.style.BottomToTopAnim);
            popWindow.setFocusable(true);
            popWindow.setOutsideTouchable(true);// 设置同意在外点击消失
            tvSavebitmap.setOnClickListener(this);
            tvCopy.setOnClickListener(this);
        }

        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    LinearLayout lyQrcodeBody;
    ImageView imgAdressqrcode;
    TextView tvCopy, tvSavebitmap;
    //    private QRCodeEncode.Builder builder;
    private Bitmap qrCodeBitmap = null;
    private Bitmap bodyBitmap = null;
    private String xiazaiuri = "";

    private void initAddressQRCode() {
//        layoutView(lyQrcodeBody,CommonUtil.px2dip(this,470),CommonUtil.px2dip(this,600));

                    /* * contentEtString：字符串内容
                    * w：图片的宽
                    * h：图片的高
                    * logo：不需要logo的话直接传null
                    * */
        qrCodeBitmap = CodeCreator.createQRCode(xiazaiuri,
                CommonUtil.dip2px(this, 160),
                CommonUtil.dip2px(this, 160),
                BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        imgAdressqrcode.setImageBitmap(qrCodeBitmap);

        bodyBitmap = CommonUtil.getBitMapFromView(lyQrcodeBody);
    }


    private void copyWalletAddress(String msg) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        if (cm != null) {
            // 创建普通字符型ClipData

            ClipData mClipData = ClipData.newPlainText("Label", msg);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
        }
        showToast(getString(R.string.profile_hint_item14));
        tvCopy.setText(getString(R.string.profile_hint_item14));
    }

    /**
     * 保存图片到指定路径
     *
     * @param context
     * @param bitmap   要保存的图片
     * @param fileName 自定义图片名称
     * @return
     */
    public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
        //系统相册目录
        String storePath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;

        LogUtil.e("storePath=" + storePath);
        // 保存图片至指定路径
//        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode";


        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        LogUtil.e("file=" + file.toString());
        try {
            LogUtil.e("file1");
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片(80代表压缩20%)
            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();
            LogUtil.e("file2");
            //发送广播通知系统图库刷新数据
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                LogUtil.e("file3");
                return true;
            } else {
                LogUtil.e("file4");
                return false;
            }
        } catch (IOException e) {
            LogUtil.e("file_err=" + e.toString());
            e.printStackTrace();
        }
        LogUtil.e("file5");
        return false;
    }
}
